﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Searching.Data;
namespace Searching.SearchEngine
{
    class SimpleSearch: Search
    {
        private PageStore store = PageStore.GetInstance();

        public WebPage[] GetReleatedPage(QueryItem[] items)
        {
            List<WebPage> result = new List<WebPage>();
            WebPage[] pages = store.GetAllPages();

            int[] relations = new int[pages.Length];

            for (int i = 0; i < pages.Length; ++i )
            {
                for (int j = 0; j < items.Length; ++j )
                {
                    relations[i] += CalcRelation(pages[i], items[j]);
                }
            }

            int[] biggest = GetBiggestFive(relations);

            for (int i = 0; i < biggest.Length; ++i)
                result.Add(pages[biggest[i]]);
            return result.ToArray();
        }


        private int CalcRelation(WebPage page, QueryItem item)
        {
            string[] keywords = page.GetKeywords();
            string[] query = item.GetKeywords();

            int relation = 0;
            for (int i = 0; i < keywords.Length; ++i )
            {
                Boolean allIn = true;
                for (int j = 0; j < query.Length; ++j )
                {
                    if (keywords[i].Equals(query[j]))
                    {
                        relation += (5 - i) * (5 - j);
                    }
                    else
                        allIn = false;
                }
                if (allIn)
                {
                    relation += 25;
                }
            }
            return relation;
        }

        private int[] GetBiggestFive(int []input)
        {
            if (input.Length == 1)
            {
                return new int[]{0};
            }

            int []temp = new int[input.Length];
            for (int i = 0; i < input.Length; ++i )
            {
                temp[i] = i;
            }

            int size = input.Length;
            while (size > 1)
            {
                int newsize = 0;
                for (int i = 0; i < size - 1; ++i )
                {
                    if (input[temp[i]] < input[temp[i+1]])
                    {
                        newsize = i + 1;
                        int t = temp[i];
                        temp[i] = temp[i + 1];
                        temp[i + 1] = t;
                    }
                }
                size = newsize;
            }

            int[] result;
            if (temp.Length < 5)
            {
                result = new int[temp.Length];
            }
            else
                result = new int[5];

            for (int i = 0; i < result.Length; ++i )
            {
                result[i] = temp[i];
            }
            return result;

        }
    }
}
